<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-xiyue-32x32.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-xiyue-16x16.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2">
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"hide","offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":"default"},
    back2top: {"enable":true,"sidebar":true,"scrollpercent":true},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":true,"preload":true},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="0 引言用md写发布到网络上的文章需要利用图床，如果图片体积太大，不仅上传图床需要时间，网页加载也要时间，所以可以考虑减小图片体积。经过一番搜索，找到了TinyPNG在线压缩网站，只需图片拖进网站，然后等待，然后下载。浏览器下载完后要切换到下载目录，剪切图片，跳回图片保存目录替换图片，如果下载时指定目录的话，下次写另一篇文章，又要换到另一个位置，烦死了！">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="基于TinyPNG所提供API的自动上传压缩可视化py脚本">
<meta property="og:url" content="http://xiiyue.gitee.io/2020/02/02/基于TinyPNG所提供API的自动上传压缩可视化py脚本/index.html">
<meta property="og:site_name" content="兮xiyue曰">
<meta property="og:description" content="0 引言用md写发布到网络上的文章需要利用图床，如果图片体积太大，不仅上传图床需要时间，网页加载也要时间，所以可以考虑减小图片体积。经过一番搜索，找到了TinyPNG在线压缩网站，只需图片拖进网站，然后等待，然后下载。浏览器下载完后要切换到下载目录，剪切图片，跳回图片保存目录替换图片，如果下载时指定目录的话，下次写另一篇文章，又要换到另一个位置，烦死了！">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/03/10hV6H.jpg">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/04/10q974.jpg">
<meta property="og:image" content="https://s2.ax1x.com/2020/02/04/10qA91.jpg">
<meta property="og:updated_time" content="2020-02-24T06:13:16.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于TinyPNG所提供API的自动上传压缩可视化py脚本">
<meta name="twitter:description" content="0 引言用md写发布到网络上的文章需要利用图床，如果图片体积太大，不仅上传图床需要时间，网页加载也要时间，所以可以考虑减小图片体积。经过一番搜索，找到了TinyPNG在线压缩网站，只需图片拖进网站，然后等待，然后下载。浏览器下载完后要切换到下载目录，剪切图片，跳回图片保存目录替换图片，如果下载时指定目录的话，下次写另一篇文章，又要换到另一个位置，烦死了！">
<meta name="twitter:image" content="https://s2.ax1x.com/2020/02/03/10hV6H.jpg">
  <link rel="canonical" href="http://xiiyue.gitee.io/2020/02/02/基于TinyPNG所提供API的自动上传压缩可视化py脚本/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>基于TinyPNG所提供API的自动上传压缩可视化py脚本 | 兮xiyue曰</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">兮xiyue曰</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

    

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://xiiyue.gitee.io/2020/02/02/基于TinyPNG所提供API的自动上传压缩可视化py脚本/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiyue">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xiyueavatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="兮xiyue曰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">基于TinyPNG所提供API的自动上传压缩可视化py脚本

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2020-02-02 19:15:12" itemprop="dateCreated datePublished" datetime="2020-02-02T19:15:12+08:00">2020-02-02</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-02-24 14:13:16" itemprop="dateModified" datetime="2020-02-24T14:13:16+08:00">2020-02-24</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/编程/" itemprop="url" rel="index"><span itemprop="name">编程</span></a></span>

                
                
              
            </span>
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="0-引言"><a href="#0-引言" class="headerlink" title="0 引言"></a>0 引言</h2><p>用md写发布到网络上的文章需要利用图床，如果图片体积太大，不仅上传图床需要时间，网页加载也要时间，所以可以考虑减小图片体积。经过一番搜索，找到了TinyPNG在线压缩网站，只需图片拖进网站，然后等待，然后下载。<br>浏览器下载完后要切换到下载目录，剪切图片，跳回图片保存目录替换图片，如果下载时指定目录的话，下次写另一篇文章，又要换到另一个位置，烦死了！</p>
<a id="more"></a>
<h2 id="1-模型的建立"><a href="#1-模型的建立" class="headerlink" title="1 模型的建立"></a>1 模型的建立</h2><p>我会为每一篇文章指定一个图片保存目录，方便以后管理，而截图时直接就将图片保存在该目录下，所以我希望直接将图片拖进程序，然后它就直接变成了压缩成品，没有其他操作。</p>
<p>窗口接收文件；一个标签，显示文字“图片”，一个标签，文字显示为拖入图片的绝对地址；一个标签，显示目前状态；一个按钮，按下则开始工作。<br>理论上，不需要按钮，但是由本人控制何时开始感觉更有安全感。</p>
<p>为了方便查看各控件的坐标，在cad中做了初步的规划，由于界面实在太简单，也不准备再更改，就没有保存二维图，在此仅列出控件几何参数。</p>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">标签</th>
<th style="text-align:center">定义名</th>
<th style="text-align:center">位置</th>
<th style="text-align:center">尺寸</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">窗体</td>
<td style="text-align:center">xiiyue</td>
<td style="text-align:center">无</td>
<td style="text-align:center">500,400</td>
</tr>
<tr>
<td style="text-align:center">静态标签</td>
<td style="text-align:center">label_s</td>
<td style="text-align:center">40,65</td>
<td style="text-align:center">60,30</td>
</tr>
<tr>
<td style="text-align:center">路径标签</td>
<td style="text-align:center">label_picfile</td>
<td style="text-align:center">130,50</td>
<td style="text-align:center">330,60</td>
</tr>
<tr>
<td style="text-align:center">状态标签</td>
<td style="text-align:center">label_state</td>
<td style="text-align:center">40,120</td>
<td style="text-align:center">420,160</td>
</tr>
<tr>
<td style="text-align:center">确认按钮</td>
<td style="text-align:center">butn</td>
<td style="text-align:center">200,305</td>
<td style="text-align:center">100,30</td>
</tr>
</tbody>
</table>
</div>
<h2 id="2-代码实现"><a href="#2-代码实现" class="headerlink" title="2 代码实现"></a>2 代码实现</h2><h3 id="2-1-窗体"><a href="#2-1-窗体" class="headerlink" title="2.1 窗体"></a>2.1 窗体</h3><p>新建类，用于创建空白控件，自动成为窗体。<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">xiiyue</span><span class="params">(QWidget)</span>:</span></span><br><span class="line">	<span class="keyword">pass</span></span><br></pre></td></tr></table></figure></p>
<p>其实不需要新建继承QWidget的类，我是边学边写，跟着写。新建类后想要运行它，在以下代码<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    app = QApplication(sys.argv)  <span class="comment"># 创建应用</span></span><br><span class="line">    xiyue = xiiyue()              <span class="comment"># 实例化</span></span><br><span class="line">    xiyue.show()                  <span class="comment"># 显示窗口</span></span><br><span class="line">    sys.exit(app.exec_())         <span class="comment"># 持续运行</span></span><br></pre></td></tr></table></figure></p>
<p>这句if使得其他文件导入此文件不会运行，而执行此文件才会运行。我本来就打算在一个文件里完成所有代码，因此不需要考虑导入的问题，不过这种格式的确有逻辑清晰的优点，这样写也没毛病。<br>写到此时用到了QWidget，QApplication，sys，因此文件开头导入模块：<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">from</span> PyQt5.QtWidgets <span class="keyword">import</span> QWidget,QApplication</span><br></pre></td></tr></table></figure></p>
<p>继续调整主窗体，改写init。<br>1，继承所有，毕竟不能影响QWidget的原本功能<br>2，设置窗体名<br>3，设置窗口大小<br>4，加载子控件</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">    super(xiiyue, self).__init__()</span><br><span class="line">    <span class="comment"># 设置窗口名</span></span><br><span class="line">    self.setWindowTitle(<span class="string">"图片压缩"</span>)</span><br><span class="line">    <span class="comment"># 定义窗口大小</span></span><br><span class="line">    self.resize(<span class="number">500</span>, <span class="number">400</span>)</span><br><span class="line">    <span class="comment"># 布置控件</span></span><br><span class="line">    self.load()</span><br></pre></td></tr></table></figure>
<p>为了保证init的简洁明了，子控件的建立和外观设定都放在了<code>load()</code>函数里。</p>
<h3 id="2-2-子控件"><a href="#2-2-子控件" class="headerlink" title="2.2 子控件"></a>2.2 子控件</h3><p>定义<code>load()</code>函数<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">load</span><span class="params">(self)</span>:</span></span><br><span class="line">	<span class="keyword">pass</span></span><br></pre></td></tr></table></figure></p>
<p>其中为各子控件的创建和设置代码</p>
<ul>
<li><p>静态标签部分</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 建标签</span></span><br><span class="line">self.label_s = QLabel(self)</span><br><span class="line"><span class="comment"># 标签位置和尺寸</span></span><br><span class="line">self.label_s.setGeometry(<span class="number">40</span>, <span class="number">65</span>, <span class="number">60</span>, <span class="number">30</span>)</span><br><span class="line"><span class="comment"># 标签格式，字体颜色红，大小15像素，加粗</span></span><br><span class="line">self.label_s.setStyleSheet(<span class="string">"color:red;font-size:15px;font-weight:bold;"</span>)</span><br><span class="line"><span class="comment"># 标签居中设置，水平垂直居中</span></span><br><span class="line">self.label_s.setAlignment(QtCore.Qt.AlignCenter)</span><br><span class="line"><span class="comment"># 标签文字</span></span><br><span class="line">self.label_s.setText(<span class="string">"图片"</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>路径标签部分</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">self.label_picfile = QLabel(self)</span><br><span class="line">self.label_picfile.setGeometry(<span class="number">130</span>, <span class="number">50</span>, <span class="number">330</span>, <span class="number">60</span>)</span><br><span class="line"><span class="comment"># 标签格式，背景白，字体大小15像素</span></span><br><span class="line">self.label_picfile.setStyleSheet(<span class="string">"background-color:white;font-size:15px;"</span>)</span><br><span class="line"><span class="comment"># 标签居中设置，左对齐，垂直居中</span></span><br><span class="line">self.label_picfile.setAlignment(QtCore.Qt.AlignLeft |QtCore.Qt.AlignVCenter)</span><br><span class="line">self.label_picfile.setText(self.file_name)</span><br><span class="line"><span class="comment"># 标签设置自动换行</span></span><br><span class="line">self.label_picfile.setWordWrap(<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>这里有个变量<code>file_name</code>没有定义，它是存放文件名的变量，在init中加上<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">self.file_name = <span class="string">''</span></span><br></pre></td></tr></table></figure></p>
<ul>
<li><p>状态标签部分</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">self.label_state = QLabel(self)</span><br><span class="line">self.label_state.setGeometry(<span class="number">40</span>, <span class="number">120</span>, <span class="number">420</span>, <span class="number">160</span>)</span><br><span class="line">self.label_state.setAlignment(QtCore.Qt.AlignCenter)</span><br><span class="line">self.label_state.setStyleSheet(<span class="string">"font-size:50px;font-weight:bold;"</span>)</span><br><span class="line">self.label_state.setText(<span class="string">"就绪"</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>确认按钮部分</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">self.butn = QPushButton(self)</span><br><span class="line">self.butn.setGeometry(<span class="number">200</span>,<span class="number">305</span>,<span class="number">100</span>,<span class="number">30</span>)</span><br><span class="line">self.butn.setText(<span class="string">"开始压缩"</span>)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>以上用到了QLabel、QPushButton和QtCore同样要导入<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> PyQt5.QtWidgets <span class="keyword">import</span> QLabel,QPushButton</span><br><span class="line"><span class="keyword">from</span> PyQt5 <span class="keyword">import</span> QtCore</span><br></pre></td></tr></table></figure></p>
<h3 id="2-3-拖入图片功能"><a href="#2-3-拖入图片功能" class="headerlink" title="2.3 拖入图片功能"></a>2.3 拖入图片功能</h3><p>现在程序的外形都有了，如图所示。</p>
<p><img src="https://s2.ax1x.com/2020/02/03/10hV6H.jpg" alt="10hV6H.jpg"></p>
<p>但是还没有相应的功能，本小节就实现运行图片拖入程序并获取位置信息。<br>在init中加入代码启用拖拽功能<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 启用拖拽</span></span><br><span class="line">self.setAcceptDrops(<span class="literal">True</span>)</span><br></pre></td></tr></table></figure></p>
<p>文件拖拽如控件时会自动调用dragEnterEvent函数，因此在类中重写此函数。<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># evn参数接收拖入事件</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">dragEnterEvent</span><span class="params">(self, evn)</span>:</span></span><br><span class="line">	<span class="comment"># 获取文件名</span></span><br><span class="line">    self.file_name=evn.mimeData().text()</span><br><span class="line">    <span class="comment"># 截取需要部分</span></span><br><span class="line">    self.file_name=self.file_name[<span class="number">8</span>:]</span><br><span class="line">    <span class="comment"># 设置路径标签文本</span></span><br><span class="line">    self.label_picfile.setText(self.file_name)</span><br></pre></td></tr></table></figure></p>
<p>路径标签中显示出路径说明一切都准备好了，可以点击按钮开始压缩。<br><code>evn.mimeData().text()</code>返回的路径开头8个字符是“file:///”，需要将其剪切。</p>
<h3 id="2-4-按钮功能"><a href="#2-4-按钮功能" class="headerlink" title="2.4 按钮功能"></a>2.4 按钮功能</h3><p>按下按钮就开始调用压缩函数，但是有一个问题，上传图片给tinypng然后返回结果需要一定的时间，而在这段时间内，程序会未响应的现象，心灰之余，该项目被我放弃了好长时间。现在闲着没事，搜索了一下，发现多线程可以解决这类问题。<br>按钮功能通过信号与槽机制实现，定义槽函数，即按钮按下后需要做的事<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">butn_job</span><span class="params">(self)</span>:</span></span><br><span class="line">	<span class="keyword">if</span> self.file_name != <span class="string">''</span>:</span><br><span class="line">		<span class="comment"># 设置状态标签文本，表明正在压缩</span></span><br><span class="line">        self.label_state.setText(<span class="string">"等"</span>)</span><br><span class="line">        <span class="comment"># 新建线程，指明该线程需执行的函数</span></span><br><span class="line">        self.thread_deal = threading.Thread(target=self.deal_pic)</span><br><span class="line">        <span class="comment"># 线程启动</span></span><br><span class="line">        self.thread_deal.start()</span><br><span class="line">    <span class="comment"># 没有拖入图片时不工作</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">    	self.label_state.setText(<span class="string">"拖入图片"</span>)</span><br></pre></td></tr></table></figure></p>
<p>线程需要threading模块<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> threading</span><br></pre></td></tr></table></figure></p>
<p>按钮的信号需要与槽连接，内置的信号为clicked函数，在init中连接<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">self.butn.clicked.connect(self.butn_job)</span><br></pre></td></tr></table></figure></p>
<h3 id="2-5-压缩"><a href="#2-5-压缩" class="headerlink" title="2.5 压缩"></a>2.5 压缩</h3><p>直接写<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">deal_pic</span><span class="params">(self)</span>:</span></span><br><span class="line">	<span class="comment"># 断开按钮信号与槽的连接，处理图片时按钮点击无反应</span></span><br><span class="line">    self.butn.blockSignals(<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># 压缩图片</span></span><br><span class="line">    source = tinify.from_file(self.file_name)</span><br><span class="line">    <span class="comment"># 保存图片</span></span><br><span class="line">    source.to_file(self.file_name)</span><br><span class="line">    <span class="comment"># 记录本月上传次数</span></span><br><span class="line">    compressions_this_month =str(tinify.compression_count)</span><br><span class="line">    <span class="comment"># 次数没地方放，就显示在标题处吧</span></span><br><span class="line">    self.setWindowTitle(<span class="string">"图片压缩"</span> + <span class="string">"本月使用："</span> + compressions_this_month)</span><br><span class="line">    <span class="comment"># 设置状态标签</span></span><br><span class="line">    self.label_state.setText(<span class="string">"就绪"</span>)</span><br><span class="line">    <span class="comment"># 恢复按钮信号与槽的连接</span></span><br><span class="line">    self.butn.blockSignals(<span class="literal">False</span>)</span><br><span class="line">    <span class="comment"># 重置路径标签</span></span><br><span class="line">    self.file_name = <span class="string">''</span></span><br><span class="line">    self.label_picfile.setText(self.file_name)</span><br></pre></td></tr></table></figure></p>
<p>需要用到tinify模块<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> tinify</span><br></pre></td></tr></table></figure></p>
<p>需要提供key<br>在程序开头就给它加上<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">tinify.key = <span class="string">"xxxxxxxxxxxxxxxxxxx"</span></span><br></pre></td></tr></table></figure></p>
<p>至此所有工作都完成，完整代码在最后，接下来是试验。</p>
<h2 id="3-实机试验"><a href="#3-实机试验" class="headerlink" title="3 实机试验"></a>3 实机试验</h2><p>我在使用的时候发现，未响应问题确实解决了，但等待时间也太久了，我加了一个计时功能以便直观感受。<br>导入time模块<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">tinify.key = <span class="string">"xxxxxxxxxxxxxxxxxxx"</span></span><br></pre></td></tr></table></figure></p>
<p>在图片压缩的两行代码上下加入时间记录函数，并将耗时显示在标题<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">t1 = time.time()</span><br><span class="line">source = tinify.from_file(self.file_name)</span><br><span class="line">source.to_file(self.file_name)</span><br><span class="line">t2 = time.time()</span><br><span class="line">t = t2 - t1</span><br><span class="line">compressions_this_month =str(tinify.compression_count)</span><br><span class="line">self.setWindowTitle(<span class="string">"图片压缩"</span> + <span class="string">"本月使用："</span> + compressions_this_month + <span class="string">"用时："</span> + str(t))</span><br></pre></td></tr></table></figure></p>
<p>随便个截图，277k，开始压缩了，看图</p>
<p><img src="https://s2.ax1x.com/2020/02/04/10q974.jpg" alt="10q974.jpg"></p>
<p>结束了，看图</p>
<p><img src="https://s2.ax1x.com/2020/02/04/10qA91.jpg" alt="10qA91.jpg"></p>
<p>37s，然后我下载了一个压缩图片的软件。</p>
<p>最后，此项目结束，有所收获，并尽量还原实际的思考过程。</p>
<h2 id="完整代码"><a href="#完整代码" class="headerlink" title="完整代码"></a>完整代码</h2><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"><span class="comment"># by xiyue</span></span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> tinify</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">from</span> PyQt5.QtWidgets <span class="keyword">import</span> QWidget,QLabel,QApplication,QPushButton</span><br><span class="line"><span class="keyword">from</span> PyQt5 <span class="keyword">import</span> QtCore</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">xiiyue</span><span class="params">(QWidget)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super(xiiyue, self).__init__()</span><br><span class="line">        <span class="comment">#定义变量</span></span><br><span class="line">        self.file_name = <span class="string">''</span></span><br><span class="line">        <span class="comment"># 窗口标题</span></span><br><span class="line">        self.setWindowTitle(<span class="string">"图片压缩"</span>)</span><br><span class="line">        <span class="comment"># 定义窗口大小</span></span><br><span class="line">        self.resize(<span class="number">500</span>, <span class="number">400</span>)</span><br><span class="line">        <span class="comment">#布置控件</span></span><br><span class="line">        self.load()</span><br><span class="line">        <span class="comment"># 启用Drops方法</span></span><br><span class="line">        self.setAcceptDrops(<span class="literal">True</span>)</span><br><span class="line">        <span class="comment">#signal and slot</span></span><br><span class="line">        self.butn.clicked.connect(self.butn_job)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">load</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#静态标签</span></span><br><span class="line">        self.label_s = QLabel(self)</span><br><span class="line">        self.label_s.setGeometry(<span class="number">40</span>, <span class="number">65</span>, <span class="number">60</span>, <span class="number">30</span>)</span><br><span class="line">        self.label_s.setStyleSheet(<span class="string">"color:red;font-size:15px;font-weight:bold;"</span>)</span><br><span class="line">        self.label_s.setAlignment(QtCore.Qt.AlignCenter)</span><br><span class="line">        self.label_s.setText(<span class="string">"图片"</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment">#路径标签</span></span><br><span class="line">        self.label_picfile = QLabel(self)</span><br><span class="line">        self.label_picfile.setGeometry(<span class="number">130</span>, <span class="number">50</span>, <span class="number">330</span>, <span class="number">60</span>)</span><br><span class="line">        self.label_picfile.setStyleSheet(<span class="string">"background-color:white;font-size:15px;"</span>)</span><br><span class="line">        self.label_picfile.setAlignment(QtCore.Qt.AlignLeft |QtCore.Qt.AlignVCenter)</span><br><span class="line">        self.label_picfile.setText(self.file_name)</span><br><span class="line">        self.label_picfile.setWordWrap(<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment">#状态标签</span></span><br><span class="line">        self.label_state = QLabel(self)</span><br><span class="line">        self.label_state.setGeometry(<span class="number">40</span>, <span class="number">120</span>, <span class="number">420</span>, <span class="number">160</span>)</span><br><span class="line">        self.label_state.setAlignment(QtCore.Qt.AlignCenter)</span><br><span class="line">        self.label_state.setStyleSheet(<span class="string">"font-size:50px;font-weight:bold;"</span>)</span><br><span class="line">        self.label_state.setText(<span class="string">"就绪"</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment">#确认按钮</span></span><br><span class="line">        self.butn = QPushButton(self)</span><br><span class="line">        self.butn.setGeometry(<span class="number">200</span>,<span class="number">305</span>,<span class="number">100</span>,<span class="number">30</span>)</span><br><span class="line">        self.butn.setText(<span class="string">"开始压缩"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 鼠标拖入事件</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dragEnterEvent</span><span class="params">(self, evn)</span>:</span></span><br><span class="line">        self.file_name=evn.mimeData().text()</span><br><span class="line">        self.file_name=self.file_name[<span class="number">8</span>:]</span><br><span class="line">        self.label_picfile.setText(self.file_name)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 按钮函数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">butn_job</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.file_name != <span class="string">''</span>:</span><br><span class="line">            self.label_state.setText(<span class="string">"等"</span>)</span><br><span class="line">            self.thread_deal = threading.Thread(target=self.deal_pic)</span><br><span class="line">            self.thread_deal.start()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.label_state.setText(<span class="string">"拖入图片"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 压缩图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">deal_pic</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.butn.blockSignals(<span class="literal">True</span>)</span><br><span class="line">        t1 = time.time()</span><br><span class="line">        source = tinify.from_file(self.file_name)</span><br><span class="line">        source.to_file(self.file_name)</span><br><span class="line">        t2 = time.time()</span><br><span class="line">        t = t2 - t1</span><br><span class="line">        compressions_this_month =str(tinify.compression_count)</span><br><span class="line">        self.setWindowTitle(<span class="string">"图片压缩"</span> + <span class="string">"本月使用："</span> + compressions_this_month + <span class="string">"用时："</span> + str(t))</span><br><span class="line">        self.label_state.setText(<span class="string">"就绪"</span>)</span><br><span class="line">        self.butn.blockSignals(<span class="literal">False</span>)</span><br><span class="line">        self.file_name = <span class="string">''</span></span><br><span class="line">        self.label_picfile.setText(self.file_name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    tinify.key = <span class="string">"xxxxxxxxxxxxxxxxxxxxxxxxx"</span></span><br><span class="line">    app = QApplication(sys.argv)</span><br><span class="line">    xiyue = xiiyue()</span><br><span class="line">    xiyue.show()</span><br><span class="line">    sys.exit(app.exec_())</span><br></pre></td></tr></table></figure>
    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/python/" rel="tag"># python</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/11/09/20191109_AnsysWorkbench_01_热源扩散/" rel="next" title="AnsysWorkbench-01-热源扩散">
                  <i class="fa fa-chevron-left"></i> AnsysWorkbench-01-热源扩散
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2020/02/19/markdown个人使用语法记录/" rel="prev" title="Markdown个人使用语法记录">
                  Markdown个人使用语法记录 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0-引言"><span class="nav-text">0 引言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-模型的建立"><span class="nav-text">1 模型的建立</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-代码实现"><span class="nav-text">2 代码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-窗体"><span class="nav-text">2.1 窗体</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-子控件"><span class="nav-text">2.2 子控件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-拖入图片功能"><span class="nav-text">2.3 拖入图片功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-按钮功能"><span class="nav-text">2.4 按钮功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-压缩"><span class="nav-text">2.5 压缩</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-实机试验"><span class="nav-text">3 实机试验</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#完整代码"><span class="nav-text">完整代码</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/xiyueavatar.JPG"
      alt="xiyue">
  <p class="site-author-name" itemprop="name">xiyue</p>
  <div class="site-description" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">6</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/xiiyue" title="GitHub &rarr; https://github.com/xiiyue" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:857319672@qq.com" title="E-Mail &rarr; mailto:857319672@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiyue</span>
</div>

        












        
      </div>
    </footer>
  </div>

  


  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/muse.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  








  <script src="/js/local-search.js?v=7.4.0"></script>








<script>
if (document.querySelectorAll('div.pdf').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/pdfobject@2/pdfobject.min.js', () => {
    document.querySelectorAll('div.pdf').forEach(element => {
      PDFObject.embed(element.getAttribute('target'), element, {
        pdfOpenParams: {
          navpanes: 0,
          toolbar: 0,
          statusbar: 0,
          pagemode: 'thumbs',
          view: 'FitH'
        },
        PDFJS_URL: '/lib/pdf/web/viewer.html',
        height: element.getAttribute('height') || '500px'
      });
    });
  }, window.PDFObject);
}
</script>


<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'forest',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>




  

  

  

  

</body>
</html>
